package com.example.mypainter

import android.Manifest
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import android.widget.Toast
import com.qw.soul.permission.SoulPermission
import com.qw.soul.permission.bean.Permission
import com.qw.soul.permission.callbcak.CheckRequestPermissionListener
import java.io.File
import java.io.FileOutputStream
import java.lang.Exception
import java.util.*


object View2PngUtil {
    fun saveViewToPngWithPermission(context: Context, view: View) {
        SoulPermission.getInstance()
            .checkAndRequestPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                object : CheckRequestPermissionListener {
                    override fun onPermissionOk(permission: Permission) {
                        saveViewToPng(context, view)
                    }

                    override fun onPermissionDenied(permission: Permission) {
                    }
                })
    }

    fun saveViewToPng(context: Context, view: View) {
        val bitmap: Bitmap = getBitmapFromView(view)
        try {
            val strPath = "/testSaveView/" + UUID.randomUUID().toString() + ".png"
            val sdCardDir: File = Environment.getExternalStorageDirectory()
            val file = File(sdCardDir, strPath)
            file.parentFile?.mkdirs()
            val fos = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
            fos.flush()
            Toast.makeText(context, "已导出：" + file.absolutePath, Toast.LENGTH_LONG).show()
        } catch (e: Exception) {
            Toast.makeText(context, "导出失败", Toast.LENGTH_LONG).show()
        }
    }

    private fun getBitmapFromView(v: View): Bitmap {
        val screenshot: Bitmap = Bitmap.createBitmap(v.width, v.height, Bitmap.Config.ARGB_8888)
        val c = Canvas(screenshot)
        c.translate(-v.scrollX.toFloat(), -v.scrollY.toFloat())
        v.draw(c)
        return screenshot
    }
}